package com.lintesis.lintesisview.webgui.rol;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;

import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zkplus.databind.BindingListModelList;
import org.zkoss.zul.Label;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listheader;
import org.zkoss.zul.Paging;
import org.zkoss.zul.SimpleConstraint;
import org.zkoss.zul.Textbox;

import com.lintesis.lintesismodel.common.hibernate.GenericDAO;
import com.lintesis.lintesismodel.common.hibernate.HibernateSearchObject;
import com.lintesis.lintesismodel.common.hibernate.Report;
import com.lintesis.lintesismodel.users.Role;
import com.lintesis.lintesismodel.users.User;
import com.lintesis.lintesismodel.users.UsrRight;
import com.lintesis.lintesisview.common.ABMDialogCtrl;
import com.lintesis.lintesisview.common.BoException;
import com.lintesis.lintesisview.common.menu.UserWorkspace;
import com.trg.search.Filter;
import com.trg.search.SearchResult;

public class RolDialogCtrl extends ABMDialogCtrl<Role>
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 6943446774386499434L;

	String rightPreffix = "role.dialog.";
	Textbox tbNombre;
	Textbox tbDescripcion;
	// Checkbox checkShowAllPermisos;
	// Textbox tbNombrePermiso;
	// Button btSearchPermiso;
	Listheader lhNombreHijo;
	Listheader lhClaveHijo;
	Label lbNombre;
	Label lbClave;
	
	//Right (Permisos)
	Listbox listboxPermisos;
	BindingListModelList listModelPermisos;
	GenericDAO<UsrRight> gdaoPermisos = new GenericDAO<UsrRight>(UserWorkspace.getInstance().gethSession());
	HibernateSearchObject<UsrRight> hsoPermisos = new HibernateSearchObject<UsrRight>(UsrRight.class);
	HashMap<String, Object> filterPermisos = new HashMap<String, Object>();
	Paging permisosPaging;
	
	//TerminalRights (Funciones)
	Listbox listboxTerminalRights;
	BindingListModelList listModelTerminalRights;
//	GenericDAO<TerminalRight> gdaoTerminalRights = new GenericDAO<TerminalRight>(UserWorkspace.getInstance().gethSession());
			
	// Companies
	Listbox listboxCompanies;
	BindingListModelList listModelCompanies;
//	GenericDAO<Company> gdaoCompany = new GenericDAO<Company>(UserWorkspace.getInstance().gethSession());

	// Stations
	Listbox listboxStations;
	BindingListModelList listModelStations;
//	GenericDAO<Station> gdaoStation = new GenericDAO<Station>(UserWorkspace.getInstance().gethSession());

	// Reports
	Listbox listboxReports;
	BindingListModelList listModelReports;
	
	int isNull = 0;
	
	@Override
	protected void doSetClearComponents()
	{
		clearComponents.add(tbNombre);
		clearComponents.add(tbDescripcion);
	}

	@Override
	protected void doSetFieldProperties()
	{
//		tbNombre.setConstraint(new SimpleConstraint(SimpleConstraint.NO_EMPTY));
//		tbDescripcion.setConstraint(new SimpleConstraint(SimpleConstraint.NO_EMPTY));
	}

	@Override
	protected void doSetReadOnlyComponents()
	{
		roComponents.add(tbNombre);
		roComponents.add(tbDescripcion);
		roComponents.add(listboxPermisos);
		// roComponents.add(checkShowAllPermisos);
		// roComponents.add(tbNombrePermiso);
		// roComponents.add(btSearchPermiso);
//		roComponents.add(listboxCompanies);
//		roComponents.add(listboxStations);
//		roComponents.add(listboxReports);
	}

	@Override
	protected void doSetValidation() throws Exception
	{
		if((entity.getRoleName()==null) || (tbNombre.getValue().isEmpty() == true)){
			isNull= 1;
			lbNombre.setStyle("color:red");
		}
		else{
			lbNombre.setStyle("color:black");
		}
		if((entity.getDescription()==null) || (tbDescripcion.getValue().isEmpty() == true)){
			isNull= 1;
			lbClave.setStyle("color:red");
		}
		else{
			lbClave.setStyle("color:black");
		}
		if(isNull==1){
			isNull = 0;
			this.doSetClearComponents();
			throw new BoException("Debe completar los datos obligatorios indicados con rojo");			
		}
//		if (listboxCompanies.getSelectedIndex() == -1)
//		{
//			throw new BoException("mustSelectOperators"));
//		}
	}

	@Override
	protected void fillBussinesObject()
	{

	}

	@Override
	protected void fillComboBoxs()
	{
		// checkShowAllPermisos.setChecked(true);
		// setSearchFiltersPermisos();
		doSearchPermisos();
		try
		{
			listModelReports = new BindingListModelList(new GenericDAO<Report>(UserWorkspace.getInstance().gethSession()).getByBussinessObject(new Report()), true);
//			listModelTerminalRights=new BindingListModelList(gdaoTerminalRights.getByBussinessObject(new TerminalRight()), true);
//			listModelCompanies = new BindingListModelList(gdaoCompany.getByBussinessObject(new Company()), true);
//			listModelStations = new BindingListModelList(gdaoStation.getByBussinessObject(new Station()), true);
		} catch (SecurityException e)
		{
			e.printStackTrace();
		} catch (IllegalArgumentException e)
		{
			e.printStackTrace();
		} catch (NoSuchMethodException e)
		{
			e.printStackTrace();
		} catch (IllegalAccessException e)
		{
			e.printStackTrace();
		} catch (InvocationTargetException e)
		{
			e.printStackTrace();
		} catch (InstantiationException e)
		{
			e.printStackTrace();
		}
	}

	@Override
	protected Role getNewEntidad()
	{
		Role role = new Role();
//		role.setUsrRights(new ArrayList<UsrRight>());
//		role.setCompanies(new ArrayList<Company>());
//		role.setStations(new ArrayList<Station>());
		return role;
	}

	@Override
	protected String getRightPreffix()
	{
		return rightPreffix;
	}

	protected void doSearchPermisos()
	{
		gdaoPermisos.clearFilters();
		hsoPermisos = new HibernateSearchObject<UsrRight>(UsrRight.class);
		hsoPermisos.addFilter(Filter.or(new Filter("key", null, Filter.OP_EMPTY), Filter.ilike("key", "%menu%")));

		for (String key : filterPermisos.keySet())
		{
			if (filterPermisos.get(key) != null && !filterPermisos.get(key).equals("%%"))
				if (filterPermisos.get(key) instanceof String)
					hsoPermisos.addFilterILike(key, filterPermisos.get(key).toString());
				else
					hsoPermisos.addFilterEqual(key, filterPermisos.get(key));
		}
		hsoPermisos.addSortAsc("name");

		SearchResult<UsrRight> initialList = gdaoPermisos.getSRBySearchObject(hsoPermisos, 0, 0);
		listboxPermisos.getPagingChild().setDetailed(true);

		listModelPermisos = new BindingListModelList(initialList.getResult(), true);
		binder.loadAll();
	}

	// public void onCheck$checkShowAllPermisos(Event event)
	// {
	// doClearSearchValuesPermisos();
	// doSearchPermisos();
	//
	// }

	// public void doClearSearchValuesPermisos()
	// {
	// hsoPermisos.clear();
	// filterPermisos.clear();
	// tbNombrePermiso.setValue(null);
	// checkShowAllPermisos.setChecked(true);
	// }

	// public void onClick$btSearchPermiso(Event e)
	// {
	// setSearchFiltersPermisos();
	// doSearchPermisos();
	// // checkShowAllPermisos.setChecked(false);
	// }

	// protected void setSearchFiltersPermisos()
	// {
	// filterPermisos.clear();
	// filterPermisos.put("name", "%" + tbNombrePermiso.getValue() + "%");
	//
	// }

	public BindingListModelList getListModelPermisos()
	{
		return listModelPermisos;
	}

	public void setListModelPermisos(BindingListModelList listModelPermisos)
	{
		this.listModelPermisos = listModelPermisos;
	}

	public BindingListModelList getListModelCompanies()
	{
		return listModelCompanies;
	}

	public void setListModelCompanies(BindingListModelList listModelCompanies)
	{
		this.listModelCompanies = listModelCompanies;
	}

	public BindingListModelList getListModelStations()
	{
		return listModelStations;
	}

	public void setListModelStations(BindingListModelList listModelStations)
	{
		this.listModelStations = listModelStations;
	}

	public BindingListModelList getListModelReports()
	{
		return listModelReports;
	}

	public void setListModelReports(BindingListModelList listModelReports)
	{
		this.listModelReports = listModelReports;
	}

	@Override
	public String getEntityName()
	{
		return "Role";
	}
	
	void doLogin() throws SecurityException, IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InvocationTargetException,
			InstantiationException
	{
		org.zkoss.zk.ui.Session session=Executions.getCurrent().getDesktop().getSession();
		UserWorkspace userWorkspace =(UserWorkspace)session.getAttribute("userWorkspace");

		User user=userWorkspace.getUser();
		
		if(!user.hasRole(this.getEntity()))
			return;
		User newSysUser=new User();
		newSysUser.setPersonId(user.getPersonId());
		List<User> sysUsers=new GenericDAO<User>(userWorkspace.gethSession()).getByBussinessObject(newSysUser);
		
		if(sysUsers.size()==0)
			return;
		newSysUser=sysUsers.get(0);
		userWorkspace.getGrantedAuthoritySet().clear();
		userWorkspace.getGrantedAuthoritySet().addAll(newSysUser.getUsrRights());
		session.setAttribute("user", newSysUser);
		
		session.setAttribute("userWorkspace", userWorkspace);

		userWorkspace.setSession(Sessions.getCurrent());

		userWorkspace.afterCreationTasks();

		Executions.sendRedirect("workspace.zul");
	}

	@Override
	protected void doSaveEntidad()
	{
		super.doSaveEntidad();
		try
		{
			doLogin();
		} catch (Exception e)
		{
			throw new RuntimeException(e.toString(),e);
		}
	}

	@Override
	protected void doUpdateEntidad()
	{
		super.doUpdateEntidad();
		try
		{
			doLogin();
		} catch (Exception e)
		{
			throw new RuntimeException(e.toString(),e);
		}
	}

	public BindingListModelList getListModelTerminalRights()
	{
		return listModelTerminalRights;
	}

	public void setListModelTerminalRights(BindingListModelList listModelTerminalRights)
	{
		this.listModelTerminalRights = listModelTerminalRights;
	}
}
